package myself.study.network.tcp.examples.ex03;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
* @Name: FileUploadServer
* @Description: 案例三：文件上传服务端
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-1-12 下午9:25:42 
* @Version: V1.0
 */
public class FileUploadServer {
	
	public static void main(String[] args) throws IOException {
		//创建服务端Socket对象
		ServerSocket server = new ServerSocket(12345) ;
		System.out.println("启动文件上传服务器...");
		//监听客户端连接
		Socket socket = server.accept() ; //阻塞
		//获取输入流对象，并包装成高效缓冲字符读取流
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())) ;
		//获取文件输出流对象，并包装成高效缓冲字符写入流
		BufferedWriter writer = new BufferedWriter(new FileWriter("keyword.java")) ;
		String line = null ;
		while((line = reader.readLine()) != null) { //阻塞
			//判断文件是否读取结束
			//if("over".equals(line)) {
			//	break ;
			//}
			//将客户端发送的文件上传到指定目录
			writer.write(line) ;
			writer.newLine() ;
			writer.flush() ;
		}
		//向客户端反馈上传状态结果
		BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())) ;
		String status = "上传成功!" ;
		writer2.write(status) ;
		writer2.newLine() ;
		writer2.flush() ;
		//释放资源
		writer.close() ;
		socket.close() ;
	}

}














